package com.redsoft.epip.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.redsoft.epip.dao.GoodsRepository;
import com.redsoft.epip.entity.Goods;
import com.redsoft.spirit.util.BeanUtils;

/**
 * 商品管理的Service.
 * 
 * <pre>
 * 商品管理的Service
 * </pre>
 * 
 * @author
 * @since 1.0
 */
@Service
@Transactional
public class GoodsService {

	@Autowired
	private GoodsRepository goodsRepository;

	public Goods getGoods(int goodsId) {
		return goodsRepository.findOne(goodsId);
	}

	/**
	 * 保存或者修改
	 * 
	 * @param goods
	 * @throws Exception
	 */
	public void save(Goods goods) throws Exception {
		if (goods.getId() != null) {
			// 修改操作
			Goods goodsOld = goodsRepository.findOne(goods.getId());
			BeanUtils.copyBeanNotNull2Bean(goods, goodsOld);
			goodsRepository.save(goodsOld);
		} else {
			// 新增操作
			goods.setCreateTime(new Date());
			goodsRepository.save(goods);
		}
	}

	/**
	 * 删除
	 * 
	 * @param id
	 */
	public void delete(int id) {
		goodsRepository.deleteById(id);
	}

	public Goods get(int id) {
		return goodsRepository.findOne(id);
	}

	public Map<String, Object> getJson(int offset, int limit, String searchKey) {
		String sql = "select *from goods g where 1=1 and g.deleted = 1";
		String countSql = "select count(1) from goods g where 1=1 and g.deleted = 1";
		Map<String, String> map = new HashMap<String, String>();

		if (searchKey != null) {
			map.put("searchKey", "%" + searchKey + "%");
			sql += " and g.name like :searchKey";
			countSql += " and g.name like :searchKey";
		}
		return goodsRepository.sqlQuery(sql, countSql, map, offset, limit, "total", "rows");
	}
}
